package net.yla.smartbus.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


/*
 * 利用HttpClient进行post请求的工具类
 */
@Component
@Deprecated
public class HttpClientUtil {
    @Value("${erpUrl}")
    private String erp;

    private static String erpUrl;

    private static String charset = "UTF-8";

    @Autowired
    public void setErpUrl() {
        HttpClientUtil.erpUrl = this.erp;
    }

    /**
     * @param url 接口访问地址
     * @param str xml字符串
     * @return
     */
    public static String doPost(String url, String str) {
        URL realUrl;
        try {
            realUrl = new URL(url);

            if ("https".equalsIgnoreCase(realUrl.getProtocol())) {
                try {
                    SslUtils.ignoreSsl();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数  
            /*    List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);  
                httpPost.setEntity(entity);  
            }   */

            StringEntity myEntity = new StringEntity(str, charset);
            httpPost.addHeader("Content-Type", "application/xml");
            httpPost.setEntity(myEntity);

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                    
                   /* if(dto.indexOf("<ROOT>")>0){
                    	dto = dto.substring(dto.indexOf("<ROOT>")+"<ROOT>".length(), dto.length()-"</ROOT>".length());
                    } */
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * application/json编码方式POST请求
     *
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost( erpUrl+url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return (JSONObject) JSON.parse(resultString);
    }

public static void sendDataErp(String json){
    doPostJson("/pub/erp/notify",json);
}

    /**
     * 利用HttpClient进行请求的工具类
     *
     * @param url    请求地址
     * @param method 请求方法
     * @param result 返回结果
     * @return
     */
    public static String doGet(String url, HttpMethod method, MultiValueMap<String, String> result) {
        RestTemplate template = new RestTemplate();
        ResponseEntity<String> forEntity = template.getForEntity(url, String.class);
        return forEntity.getBody();
    }


    /**
     * 利用HttpClient发送GET请求并返回 JSON 结果
     *
     * @param url
     * @return
     */
    public static JSONObject doGetForJson(String url) {
        JSONObject resultJsonObject = null;

        CloseableHttpClient httpClient = HttpClients.createDefault();

//
        StringBuffer urlStringBuilder = new StringBuffer(url);

        StringBuffer entityStringBuilder = new StringBuffer();

        HttpGet httpGet = new HttpGet(urlStringBuilder.toString());
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //得到httpResponse的状态响应码
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == HttpStatus.SC_OK) {
            //得到httpResponse的实体数据
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), charset), 8 * 1024);
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        entityStringBuilder.append(line);
                    }
                    String json = entityStringBuilder.toString();
                    resultJsonObject = JSON.parseObject(json);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return resultJsonObject;
    }

}  
